/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.purchasereceive;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.TransactionValidate;
import com.lightkits.common.db.entity.FndUomBase;
import com.lightkits.common.db.entity.ScmPoLine;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.validate.IntegrityValidator;
import com.lightkits.framework.soa.hzero.executor.ServiceExecutor;
import com.lightkits.wms.database.dao.WmsScmPoLineMapper;
import com.lightkits.wms.database.model.PurLineModel;
import com.lightkits.wms.dto.purchasereceive.GetPoLineListRequestType;
import com.lightkits.wms.dto.purchasereceive.GetPoLineListResponseType;
import com.lightkits.wms.dto.purchasereceive.models.PoLineDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购订单行历史接受列表
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/4/25 23:31
 */
@Component
public class PoLineListExecutor implements ServiceExecutor<GetPoLineListRequestType, GetPoLineListResponseType> {
    private final Logger logger = LoggerFactory.getLogger(PoLineListExecutor.class);

    private final WmsScmPoLineMapper wmsScmPoLineMapper;

    @Autowired
    public PoLineListExecutor(WmsScmPoLineMapper wmsScmPoLineMapper) {
        this.wmsScmPoLineMapper = wmsScmPoLineMapper;
    }

    @Override
    public GetPoLineListResponseType service(GetPoLineListRequestType request) {
        GetPoLineListResponseType response = new GetPoLineListResponseType();
        response.setSuccessful(true);
        try {
            IntegrityValidator.begin().validate(request.getPoLineId(), "Purcharse Line Id");

            TransactionValidate check = TransactionValidate.beginValidity(ScmPoLine.class);
            check.checkIdValidity(ObjectUtil.toString(request.getPoLineId()), "ID");
            List<PurLineModel> models = wmsScmPoLineMapper.getPoLineRecordByLineId(request.getPoLineId());

            if (ObjectUtil.isNullOrEmpty(models)) {
                response.setPoLineDTOS(new ArrayList<>());
                return response;
            }
            response.setPoLineDTOS(this.convertLine(models));
        } catch (LightKitsBizException e) {
            response.setSuccessful(false);
            String mes = StringUtils.substringAfterLast(e.getMessage(), ":");
            response.setMessage(ObjectUtil.isNullOrEmpty(mes) ? e.getMessage() : mes);
        } catch (Exception e) {
            e.printStackTrace();
            response.setSuccessful(false);
            response.setMessage("get Purchase List Error");
        }
        return response;
    }

    /**
     * 历史列表转换
     *
     * @param models 数据库中查询的历史列表
     * @return PoLineDTO
     **/
    private List<PoLineDTO> convertLine(List<PurLineModel> models) {
        List<PoLineDTO> dtos = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
        try {
            models.forEach(model -> {
                PoLineDTO dto = new PoLineDTO();
                dto.setPoLineId(model.getPoLineId());
                dto.setItemId(model.getItemId());
                dto.setUomId(model.getUomId());
                dto.setUomName(model.getUomName());
                dto.setUomCode(model.getUomCode());
                dto.setLotCode(model.getLotCode());
                dto.setItemCode(model.getItemCode());
                dto.setItemDesc(model.getItemDesc());
                //根据单位中deciamal_number字段的保留小数位
                FndUomBase uomBase = new FndUomBase().selectOne(new EntityWrapper()
                        .eq(FndUomBase.UOM_CODE, model.getUomName()));
                if (ObjectUtil.isEmpty(uomBase)) {
                    dto.setDemandQty(model.getDemandQty().toString());
                    dto.setReceiveQty(model.getReceiveQty().toString());
                } else {
                    dto.setReceiveQty(model.getReceiveQty()
                            .setScale(uomBase.getDecimalNumber().intValue(),
                                    BigDecimal.ROUND_HALF_UP).toString());
                    dto.setDemandQty(model.getDemandQty()
                            .setScale(uomBase.getDecimalNumber().intValue(),
                                    BigDecimal.ROUND_HALF_UP).toString());
                }
                dto.setDemandDate(df.format(model.getDemandDate()));
                dto.setTicketLineId(model.getTicketLineId());
                dto.setReceiveWarehouseId(model.getReceiveWarehouseId());
                dto.setReceiveWarehouseName(model.getReceiveWarehouseName());
                dtos.add(dto);
            });
        } catch (Exception e) {
            logger.error("Po convertLine.error", e);
        }
        return dtos;
    }
}